package lib

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
)

const (
	GenerateCouponUrl string = "http://www.ymiot.net/BizCouponSolution/QRcodeCreate" //生成优惠券
)

//QRCodeCreate 生成二维码
func QRCodeCreate(client http.Client, request CreateQrCodeRequest, ctx RequestContext) (*CreateQrCodeResponse, error) {
	requestFormUrls := fmt.Sprintf("CouponSolution_ID=%d&SumCount=%d", request.CouponSolutionId, request.SumCount)
	r, err := http.NewRequest("POST", GenerateCouponUrl, bytes.NewReader([]byte(requestFormUrls)))
	if err != nil {
		return nil, err
	}

	defer func() {
		_ = r.Body.Close()
	}()
	SetHeader(r)
	ctx.SetHttpCookie(r)
	resp, err := client.Do(r)
	if err != nil {
		return nil, err
	}

	respData, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	var rev CreateQrCodeResponse
	err = json.Unmarshal(respData, &rev)
	if err != nil {
		return nil, err
	} else {
		return &rev, nil
	}
}
